package cn.ydxlm.paylib.wx;

import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;

import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import cn.ydxlm.paylib.PayCallback;
import cn.ydxlm.paylib.PayConfig;

import java.util.Map;

public class WxPay implements IWXAPIEventHandler {
    private static final String TAG = "WxPay";
    private static final String APP_ID = "wxf068f7bd939ad65d";
    private IWXAPI api;
    private Activity mActivity;
    private PayCallback mPayCallback;

    public static WxPay getInstance() {
        return Holder.ourInstance;
    }

    private WxPay() {
    }

    /**
     * 调支付的方法
     * <p>
     * 注意： 每次调用微信支付的时候都会校验 appid 、包名 和 应用签名的。 这三个必须保持一致才能够成功调起微信
     *
     * @param map
     */
    public void pay(Activity activity, Map<String, Object> map) {
        mActivity = activity;
        api = WXAPIFactory.createWXAPI(activity, APP_ID);
        api.registerApp(APP_ID);
        //这里的bean，是服务器返回的json生成的bean
        PayReq payRequest = new PayReq();
        payRequest.appId = APP_ID;
        payRequest.partnerId = (String) map.get("partnerid");
        payRequest.prepayId = (String) map.get("prepayid");
        payRequest.packageValue = "Sign=WXPay";//固定值
        payRequest.nonceStr = (String) map.get("noncestr");
        payRequest.timeStamp = (String) map.get("timestamp");
        payRequest.sign = (String) map.get("sign");
        //发起请求，调起微信前去支付
        api.sendReq(payRequest);
    }

    public void onCreate(Intent intent, Activity activity) {
        mActivity = activity;
        api = WXAPIFactory.createWXAPI(activity, null);
        api.handleIntent(intent, this);
    }

    public void handleIntent(Intent intent) {
        api.handleIntent(intent, this);
    }

    public void setPayCallback(PayCallback payCallback) {
        mPayCallback = payCallback;
    }

    @Override
    public void onReq(BaseReq req) {
        Toast.makeText(mActivity, "支付参数验证失败！", Toast.LENGTH_SHORT).show();
        PayConfig.log("onReq, 失败 " + req.transaction);
        if (mPayCallback == null) {
            return;
        }
    }

    /**
     * 处理结果回调
     *
     * @param resp
     */
    @Override
    public void onResp(BaseResp resp) {
        PayConfig.log("onPayFinish, errCode = " + resp.errCode);
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            switch (resp.errCode) {
                case 0://支付成功
                    Toast.makeText(mActivity, "支付成功", Toast.LENGTH_SHORT).show();
                    PayConfig.log("onResp: resp.errCode = 0   支付成功");
                    if (mPayCallback == null) {
                        return;
                    }
                    mPayCallback.onSuccess(null);
                    break;
                case -1://错误，可能的原因：签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等
                    Toast.makeText(mActivity, "支付错误", Toast.LENGTH_SHORT).show();
                    PayConfig.log("onResp: resp.errCode = -1  支付错误");
                    if (mPayCallback == null) {
                        return;
                    }
                    mPayCallback.onError(null, "支付失败");
                    break;
                case -2://用户取消，无需处理。发生场景：用户不支付了，点击取消，返回APP。
                    PayConfig.log("onResp: resp.errCode = -2  用户取消");
                    Toast.makeText(mActivity, "用户取消", Toast.LENGTH_SHORT).show();
                    if (mPayCallback == null) {
                        return;
                    }
                    mPayCallback.onError(null, "支付取消");
                    break;
                default:
                    if (mPayCallback == null) {
                        return;
                    }
                    mPayCallback.onError(null, "支付异常");
                    break;
            }
            mActivity.finish();//这里需要关闭该页面
        }
    }


    private static class Holder {
        private static final WxPay ourInstance = new WxPay();
    }
}
